<script setup lang="ts">
import {ref, getCurrentInstance, computed, inject, type Ref, onMounted} from 'vue'
import { Search, MuteNotification, Setting, User, ArrowLeft } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

//获取路由实例
const router = useRouter();

// 导航到聊天详情页
const navigateToChatBox = async (record: any) => {
  try {
    // 获取当前用户ID
    const currentUserId = currentUser.value?.id;
    if (!currentUserId) {
      ElMessage.error('当前用户信息缺失');
      return;
    }

    // 获取对方用户ID（从记录中提取）
    // 记录的发送者ID（可能是对方或自己）
    const senderId = record.senderId;
    // 记录的接收者ID
    const receiverId = record.receiverId;

    // 对方用户ID：如果发送者是自己，则对方是接收者；反之则是发送者
    const otherUserId = senderId === currentUserId ? receiverId : senderId;

    if (!otherUserId) {
      console.error('无法确定对方用户ID:', record);
      ElMessage.error('无法获取聊天对象信息');
      return;
    }

    // 先查询当前用户与对方的所有聊天记录
    await searchData(currentUserId, otherUserId);

    // 导航到聊天页，传递参数
    router.push({
      name: 'chatbox',
      params: {
        currentUserId: currentUserId.toString(),
        otherUserId: otherUserId.toString()
      }
    });
  } catch (error) {
    console.error('导航失败:', error);
    ElMessage.error('进入聊天页失败，请重试');
  }
};

// 获取全局属性
const global = getCurrentInstance()?.appContext.config.globalProperties;

//注入全局用户状态
const userState = inject<Ref<{
  id: number;
  username: string;
  password: string;
  phone: string;
  email: string;
  avatar: string
  role: string;
  status: number;
  created_at: string;
  updated_at: string;
}>>('userState')

// 获取当前用户
const currentUser = computed(() => userState?.value || null)

// 查询聊天对象，修改为接收参数并更新数据
const chatObject = async (userId: number) => {
  try {
    const resp = await global.$http.get('backend/chatObject', {
      params: {
        id: userId
      }
    });
    // 后端返回的是 ChatRecords 数组，将数据赋值给 chatRecords
    if (resp.data && Array.isArray(resp.data)) {
      chatRecords.value = resp.data;
    }
    console.log(resp.data);
  } catch (error) {
    console.error('查询聊天对象失败:', error);
    ElMessage.error('查询聊天对象失败，请重试！');
  }
};

onMounted(() => {
  if (currentUser.value?.id) {
    chatObject(currentUser.value.id);
  }
});

// 定义变量
const id = ref<number | null>(null); // 存储输入框的整数ID
const chatRecords = ref<any[]>([]); // 存储后端返回的聊天记录
const loading = ref(false); // 加载状态
const currentSession = ref<string | null>(null); // 当前选中的会话ID
const showSessions = ref(true); // 是否显示会话列表
const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))
// 处理输入框搜索逻辑
const handleSearch = async () => {
  // 获取当前用户ID
  const currentUserId = currentUser.value?.id;
  if (!currentUserId) {
    ElMessage.error('当前用户信息缺失，无法搜索');
    return;
  }

  // 获取输入框中的目标用户ID
  const targetUserId = id.value;
  if (targetUserId === null || isNaN(targetUserId)) {
    ElMessage.warning('请输入有效的用户ID（整数）');
    return;
  }

  // 调用searchData
  await searchData(currentUserId, targetUserId);
};

//查询两个用户之间的所有聊天记录（双向）
const searchData = async (currentUserId: number, otherUserId: number) => {
  loading.value = true;
  chatRecords.value = []; // 清空现有数据

  try {
    const resp = await global.$http.get('/backend/chatRecords', {
      params: {
        // 传递两个用户ID，后端查询
        senderId: user.value.id,
        receiverId: otherUserId
      }
    });

    if (resp.data && Array.isArray(resp.data)) {
      // 按时间升序排序
      chatRecords.value = resp.data.sort(
          (a: any, b: any) => new Date(a.sendTime).getTime() - new Date(b.sendTime).getTime()
      );
      ElMessage.success(`获取到 ${resp.data.length} 条聊天记录`);
    } else {
      ElMessage.info('未找到相关聊天记录');
    }
  } catch (err) {
    console.error('查询聊天记录失败:', err);
    ElMessage.error('获取聊天记录失败，请重试！');
  } finally {
    loading.value = false;
  }
};

// 按会话分组聊天记录
const groupedSessions = computed(() => {
  const sessions: Record<string, { userIds: string[]; messages: any[] }> = {};

  chatRecords.value.forEach(record => {
    // 生成会话ID
    const userIds = [record.senderId, record.receiverId].sort();
    const sessionId = `${userIds[0]}-${userIds[1]}`;

    if (!sessions[sessionId]) {
      sessions[sessionId] = {
        userIds,
        messages: []
      };
    }

    // 添加消息并按时间排序
    sessions[sessionId].messages.push(record);
    sessions[sessionId].messages.sort((a, b) =>
        new Date(a.sendTime).getTime() - new Date(b.sendTime).getTime()
    );
  });

  return Object.values(sessions);
});

// 获取当前会话的消息
const currentMessages = computed(() => {
  if (!currentSession.value) return [];

  const session = groupedSessions.value.find(
      s => `${s.userIds[0]}-${s.userIds[1]}` === currentSession.value
  );

  return session?.messages || [];
});

// 获取对方用户ID
const getOtherUserId = (session: { userIds: string[] }) => {
  return session.userIds[0] === (id.value?.toString() || '')
      ? session.userIds[1]
      : session.userIds[0];
};

// 切换会话
const switchSession = (sessionId: string) => {
  currentSession.value = sessionId;
  showSessions.value = false;
};

// 返回会话列表
const backToSessions = () => {
  showSessions.value = true;
};

// 格式化时间
const formatTime = (sendTime: string) => {
  const date = new Date(sendTime);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 清空聊天记录
const clearChatRecords = () => {
  ElMessageBox.confirm(
      '确定要清空所有聊天记录吗？此操作不可恢复。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    chatRecords.value = [];
    ElMessage.success('聊天记录已清空');
  }).catch(() => {
    // 用户取消操作
  });
};

// 获取用户头像URL
const getAvatarUrl = (userId: string | number, record?: any) => {
  const user = findUserInRecord(userId, record);
  if (user && user.avatar) {
    return user.avatar;
  }
  // 默认头像（未查询到头像时使用）
  return `https://picsum.photos/seed/${userId}/200/200`;
};

// 获取用户头像显示文本
const getAvatarText = (userId: string | number) => {
  // 从userList中获取用户名首字母
  const user = findUserInRecord(userId);
  return user?.username?.charAt(0).toUpperCase() || 'U';
};

// 获取用户名（直接使用当前记录userList中的username）
const getUserName = (userId: string | number, record?: any) => {
  const user = findUserInRecord(userId, record);
  return user?.username || `用户${userId}`; // 兜底显示用户ID
};

//根据 id 搜索聊天记录
const findUserInRecord = (userId: string | number, record?: any) => {
  // 立即检查 userId 有效性
  if (userId === undefined || userId === null) {
    console.warn('[findUserInRecord] 无效的userId:', userId);
    return null;
  }

  // 将 userId 转换为字符串一次，避免重复转换
  const userIdStr = userId.toString();

  // 优先从当前记录的userList中查找
  if (record && Array.isArray(record.userList) && record.userList.length > 0) {
    // 查找匹配ID的用户
    const matchedUser = record.userList.find(
        (user: any) => user && user.id !== undefined && user.id.toString() === userId.toString()
    );

    if (matchedUser) {
      return matchedUser;
    }

    // 如果没找到，返回第一个有效用户（避免返回空对象）
    const firstValidUser = record.userList.find(user => user && user.id !== undefined);
    if (firstValidUser) {
      return firstValidUser;
    }
  }

  // 匹配当前用户
  if (currentUser.value && currentUser.value.id.toString() === userId.toString()) {
    return currentUser.value;
  }

  // 兜底返回null
  return null;
};
// 添加返回方法
const handleBack = () => {
  router.go(-1); // 返回上一页
};
</script>

<template>
  <div class="settled">
    <!-- 添加返回按钮 -->
    <div class="header-with-back">
      <div class="back-button" @click="handleBack">
        <svg viewBox="0 0 24 24" width="24" height="24">
          <path fill="currentColor" d="M15.41 16.59L10.83 12l4.58-4.59L14 6l-6 6 6 6 1.41-1.41z"/>
        </svg>
      </div>
    </div>
    <div class="header">
      <el-row>
        <el-col class="header_left" :span="22">
          <!-- 根据状态显示标题 -->
          <div v-if="showSessions">
            消息
            <el-button
                type="text"
                class="header_left_btn"
                @click="clearChatRecords"
                icon="Brush">
              清除
            </el-button>
          </div>
          <div v-else class="flex items-center">
            <el-button type="text" @click="backToSessions">
              <el-icon><ArrowLeft /></el-icon>
            </el-button>
            {{ getOtherUserId(groupedSessions.find(s =>
              `${s.userIds[0]}-${s.userIds[1]}` === currentSession) || { userIds: [] }) }}
          </div>
        </el-col>
        <el-col class="header_right" :span="2">
          <el-icon class="header_right_icon"><Setting /></el-icon>
        </el-col>
      </el-row>
    </div>
  </div>

  <!-- 输入框区域 -->
  <div class="search">
    <el-row>
      <el-col :span="24">
        <el-input
            v-model.number="id"
            placeholder="请输入整数ID"
            @keyup.enter="handleSearch"
            clearable>
          <template #prefix>
            <el-icon class="el-input__icon"><Search /></el-icon>
          </template>
        </el-input>
      </el-col>
    </el-row>
  </div>

  <!-- 数据展示区域 -->
  <div class="records-container">
    <!-- 无数据时显示空状态 -->
    <el-empty
        v-if="chatRecords.length === 0 && !loading"
        description="暂无数据"
        style="margin-top: 50px;"
    />
  </div>

  <!-- 聊天记录显示区域 -->
  <div class="custom-chat-records" v-if="chatRecords.length > 0">
    <div
        v-for="(record, index) in chatRecords"
        :key="record.id || index"
        class="chat-record-item flex items-start p-3 cursor-pointer"
        @click="navigateToChatBox(record)"
    >
      <!-- 左侧头像区域 -->
      <div class="avator">
        <el-avatar
            :size="50"
            :src="getAvatarUrl(record.senderId, record)"
            :text="getAvatarText(record.senderId, record)"
            class="border-2"
            :class="{'border-primary': record.senderId === currentUser.value?.id}"
        ></el-avatar>
      </div>


      <div>
        <!-- 用户名 -->
        <div class="user_id">
          {{ getUserName(record.senderId, record) }}  <!-- 传递record -->
        </div>

        <!-- 消息内容 -->
        <div class="msg_content">
          {{ record.messageContent }}
        </div>
      </div>

      <!-- 右侧消息内容区域 -->
      <div class="context">
        <!-- 上方名称和时间 -->
        <div class="time">
          <div class="text-xs text-gray-500">
            {{ formatTime(record.sendTime) }}
          </div>
        </div>
      </div>
    </div>
  </div>

</template>

<style scoped>
.settled{
  position: sticky;
  background-color: white;
  z-index: 1000;
  top: 0;
}

.header{
  margin: 5px 0px;
}

.header_left{
  display: flex;
  align-items: center;
  padding-left: 10px;
  font-size: 20px;
  font-weight: bold;
}

.header_left_btn {
  width: 80px;
  height: 20px;
  display: inline-flex;
  align-items: center;
  background-color: #f5f7fa;
  margin-left: 5px;
  border-radius: 4px;
  color: #999 !important;
}

.header_right{
  display: flex;
  align-items: center;
  justify-content: end;
}

.header_right_icon{
  font-size: 15px;
  margin-right: 10px;
}

.search{
  width: 95%;
  margin: 5px auto;
}

.records-container {
  width: 95%;
  margin: 0 auto;
}

.session-card {
  border: none;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.session-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.sent {
  display: flex;
  justify-content: flex-end;
}

.sent .message-content {
  text-align: right;
}

.sent .message-content .px-3 {
  background-color: #409eff;
  color: white;
}

.received .message-content .px-3 {
  background-color: #f0f2f5;
}

.scrollbar-wrapper {
  overflow: auto;
}

.bottom-nav-wrapper {
  position: fixed;
  bottom: 0;
  width: 100%;
  background-color: #fff;
  border-top: 2px solid #eee;
  z-index: 999;
}

.bottom-nav {
  justify-content: space-around;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 5px 0;
  text-align: center;
  cursor: pointer;
}

#icon {
  font-size: 25px;
  margin-bottom: 4px;
  display: inline-block;
  width: 25px;
  height: 25px;
  line-height: 1.2;
  text-align: center;
  border-radius: 8px;
}

.text {
  font-size: 12px;
}

.custom-chat-records {
  margin: 10px 10px;
}

.chat-record-item {
  display: flex;
  background-color: transparent;
  padding: 8px 0;
}

.chat-record-item:hover {
  background-color: transparent;
}

.user_id{
  margin-left: 10px;
}

.msg_content{
  margin-left: 10px;
}

.context{
  width: 100%;
  position: relative;
}

.time{
  position: absolute;
  right: 0;
  bottom: 0;
}


</style>